import pandas as pd
import re

# 假设数据已加载到DataFrame中
df = pd.read_csv('warehouse_scenery.csv')


def convert_playtime_to_hours(play_time):
    if pd.isna(play_time):
        return None  # 处理缺失值

    # 尝试处理范围值（如"3小时 - 4小时"）
    if '-' in str(play_time):
        times = str(play_time).split('-')
        start = parse_single_time(times[0].strip())
        end = parse_single_time(times[1].strip())
        if start is not None and end is not None:
            return (start + end) / 2  # 取平均值
        return None

    return parse_single_time(play_time)


def parse_single_time(time_str):
    if pd.isna(time_str):
        return None

    # 处理中文单位
    time_str = str(time_str)

    # 尝试提取数值和单位
    match = re.match(r'([\d.]+)\s*([a-zA-Z\u4e00-\u9fff]+)?', time_str)
    if not match:
        return None

    value, unit = match.groups()
    value = float(value)

    # 如果没有单位，假设是小时
    if unit is None:
        return value

    # 根据单位转换
    unit = unit.lower()
    if any(word in unit for word in ['hour', 'h', '小时', '时']):
        return value
    elif any(word in unit for word in ['minute', 'min', '分钟', '分']):
        return value / 60
    elif any(word in unit for word in ['day', 'd', '天']):
        return value * 24
    else:
        return None  # 未知单位


# 应用转换函数
df['playtime_hours'] = df['play_time'].apply(convert_playtime_to_hours)

# 检查转换结果
print(df[['play_time', 'playtime_hours']].head())

# 保存清洗后的数据
df.to_csv('cleaned_warehouse_scenery.csv', index=False)